package itsm.isperp.module.controller;

import itsm.isperp.framework.core.context.ContextHolder;
import itsm.isperp.framework.domain.IUser;
import itsm.isperp.framework.security.license.LicenseValidata;
import itsm.isperp.framework.web.request.JqGridFilterRuleOp;
import itsm.isperp.framework.web.request.JqGridRequest;
import itsm.isperp.module.entity.app.AppDict;
import itsm.isperp.module.entity.app.AppMenu;
import itsm.isperp.module.entity.app.AppUploadFile;
import itsm.isperp.module.service.app.AppDictService;
import itsm.isperp.module.service.app.AppMenuService;
import itsm.isperp.module.service.app.AppUploadFileService;
import itsm.isperp.module.service.app.AppUserService;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

/**
 * 系统控制器（初次进入系统）
 * 
 * @author lizx
 * @date 2013-1-7
 * @version V1.0
 */
@Controller
@RequestMapping("")
public class MainController {

  @Autowired
  protected AppMenuService appMenuService;

  /**
   * 构造菜单的路径
   * 
   * @param id
   *          模块菜单id
   * @return
   * @throws IOException
   */
  @LicenseValidata()
  @RequestMapping(value = { "main", "" }, method = RequestMethod.GET)
  public ModelAndView main(String id, HttpServletRequest req,
      HttpServletResponse response) throws IOException {
    // 如果id为空则加载顶级菜单及第一个菜单的二及菜单
    ModelAndView mv = new ModelAndView("main");
    IUser user = ContextHolder.getLoginUser();
    List<AppMenu> roots = this.appMenuService.findUserRootMenu();
    mv.addObject("user", user);
    AppUserService appUserService = ContextHolder
        .getSpringBean("appUserService");
    Map<String, Object> tUser = appUserService.findOneDetailByUsername(user
        .getUsername());
    if (tUser.get("department_treenode_path") != null)
      mv.addObject("department_treenode_path",
          tUser.get("department_treenode_path").toString());
    if (tUser.get("customer_id") != null)
      mv.addObject("customer_id", tUser.get("customer_id").toString());
    mv.addObject("curUserName", user.getUsername());

    mv.addObject("root", roots);
    String noHeader = req.getParameter("noHeader");
    if (StringUtils.isNoneBlank(noHeader))
      mv.addObject("noHeader", noHeader);
    AppDictService appDictService = ContextHolder
        .getSpringBean("appDictService");
    JdbcTemplate jdbcTemplate = ContextHolder
        .getSpringBean("jdbcTemplate");
    List<AppDict> alarmList = appDictService.findByType("ALARM_SYSTEM");
    int alarmSize=0;
    boolean areSeeJk=false;
    String sql="SELECT COUNT(1) c FROM v_app_user_role WHERE app_user_name='"+user.getUsername()+"' AND NAME='监控系统'";
    int c=jdbcTemplate.queryForObject(sql, Integer.class);
    if(c>0)
      areSeeJk=true;
    if (alarmList.size() > 0 && areSeeJk)
    {
      alarmSize=alarmList.size();
      mv.addObject("alarmSize", alarmSize);
      mv.addObject("alarmList", alarmList);
    }
      
    return mv;

  }

  @LicenseValidata()
  @RequestMapping(value = "main/login", method = RequestMethod.GET)
  public ModelAndView login(String error, HttpServletRequest req,
      HttpServletResponse resp) throws IOException {

    String ajaxHeader = req.getHeader("X-Requested-With");
    if ("XMLHttpRequest".equals(ajaxHeader)) {
      // 判断这个是ajax请求
      resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
      return null;
    }

    ModelAndView mv = new ModelAndView("login");

    boolean nocheck = true;

    mv.addObject("nocheck", nocheck);

    String msg = "";
    String msgType = "";
    if (StringUtils.isEmpty(error)) {
      msgType = "welcome";
      msg = "欢迎登录!";
    } else {
      msgType = "failure";
      switch (error) {
      case "session":
        msg = "欢迎登录!";
        break;
      case "denied":
        Object obj = req.getAttribute("SPRING_SECURITY_403_EXCEPTION");
        if (obj != null) {
          AccessDeniedException adx = (AccessDeniedException) obj;
          msg = adx.getMessage();
        } else {
          msg = "欢迎登录!";
        }

        break;
      case "true":
        msg = "用户或密码错误,登录失败!";
        break;
      case "locked":
        msg = "用户无效!";
        break;
      case "disabled":
        msg = "用户被禁用!";
        break;
      case "sessionMax":
        msg = "用户已经登录，系统不允许重复登陆!";
        break;
      case "nr":
        msg = "没有赋予角色权限!";
        break;

      }
    }
    mv.addObject("error", error);
    mv.addObject("msg", msg);
    mv.addObject("msgType", msgType);
    mv.addObject("companyName", ContextHolder.getConfigByKey("companyName"));
    AppUploadFileService appUploadFileService = ContextHolder
        .getSpringBean("appUploadFileService");
    JqGridRequest request = new JqGridRequest();
    request.addFilterRule("source_id", JqGridFilterRuleOp.eq, "bgImg");
    AppUploadFile aplf = appUploadFileService.findOneByRequest(request);
    if (aplf != null) {
      mv.addObject("bgImg", aplf.getPath());
    } else {
      mv.addObject("bgImg", "img/login/1.png");
    }
    return mv;
  }
}
